package com.mainbo.androidframework.utils;

import android.util.Log;

import org.apache.log4j.Layout;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.RollingFileAppender;

import java.io.IOException;

/**
 * Created by lsmtty on 2016/3/2.
 */
public class LogUtil {
    private static boolean isDebug = true;
    private static final String TAG = LogUtil.class.getSimpleName();
    // private static boolean isDebug = true;

    private static Logger uplusLogger;
    private static final Logger rootLogger = Logger.getRootLogger();
    private static RollingFileAppender rollingFileAppender;
    static {

        final Layout fileLayout = new PatternLayout(
                "%d{yyyy-MM-dd HH:mm:ss,SSS} [%p] - %t - %m%n");
        try {
            rollingFileAppender = new RollingFileAppender(fileLayout,
                    FileHelper.getWorkLogFile().toString());
            rollingFileAppender.setMaxBackupIndex(2);// 最大保存(2+1)=3个日志文件
            rollingFileAppender.setMaximumFileSize(1024 * 512);// 每个文件大小512KB
            rollingFileAppender.setImmediateFlush(false);
            rollingFileAppender.setBufferedIO(true);
            rollingFileAppender.setBufferSize(1024 * 8); // 文件缓冲大小默认8KB
            rollingFileAppender.setAppend(true);
            rootLogger.addAppender(rollingFileAppender);
            rootLogger.setLevel(Level.DEBUG);
            uplusLogger = Logger.getLogger("UplusLogger");
        } catch (IOException e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

    /**
     * 打印verbose信息
     *
     * @param tag
     * @param msg
     */
    public static int v(String tag, String msg) {
        return println(Log.VERBOSE, tag, msg);
    }

    /**
     * 打印调试信息
     *
     * @param tag
     * @param msg
     */
    public static int d(String tag, String msg) {
        return println(Log.DEBUG, tag, msg);
    }

    /**
     * 打印信息
     *
     * @param tag
     * @param msg
     */
    public static int i(String tag, String msg) {
        return println(Log.INFO, tag, msg);
    }

    /**
     * 打印警告信息
     *
     * @param tag
     * @param msg
     */
    public static int w(String tag, String msg) {
        return println(Log.WARN, tag, msg);
    }

    /**
     * 打印错误级别Log 信息
     *
     * @param tag
     * @param msg
     */
    public static int e(String tag, String msg) {
        return println(Log.ERROR, tag, msg);
    }

    /**
     * 正式环境INFO级别以上的才输出到文件,debug状态全部输出到文件.
     *
     * @param priority
     * @param tag
     * @param msg
     * @return
     */
    private static int println(int priority, String tag, String msg) {
        int resultCode = -1;
        if (msg == null) {
            msg = "";
        }
        if (isDebug) {
            resultCode = Log.println(priority, tag, msg);
            writeFile(priority, tag, msg);
        } else {
            if (priority >= Log.INFO) {
                writeFile(priority, tag, msg);
            }
        }
        return resultCode;
    }

    private static void writeFile(int priority, String tag, String msg) {
        Level level;
        switch (priority) {
            case Log.VERBOSE:
            case Log.DEBUG:
                level = Level.DEBUG;
                break;
            case Log.INFO:
                level = Level.INFO;
                break;
            case Log.WARN:
                level = Level.WARN;
                break;
            case Log.ERROR:
                level = Level.ERROR;
                break;
            default:
                throw new IllegalArgumentException("level is " + priority);
        }
        writeFile(level, tag, msg);
    }

    private static void writeFile(Level level, String tag, String msg) {
        rootLogger.setLevel(level);
        rollingFileAppender.setImmediateFlush(false);
        String message = tag + " - " + msg;
        uplusLogger.log(level, message);
    }

    /**
     * 主动刷日志到文件。例如：用户主动退出app，crash，切到后台（10分钟刷新一次日志）
     *
     * @param tag
     */
    public static void flushLog(String tag) {
        rollingFileAppender.setImmediateFlush(true);
        rootLogger.setLevel(Level.INFO);
        Log.d(TAG, tag + " - flushLog");
        uplusLogger.info(tag + " - ####flush log####");
    }
}
